using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 修改供应商命令处理器
    /// </summary>
    public class UpdateSupplierCommandHandler : IRequestHandler<UpdateSupplierCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateSupplierCommandHandler> _logger;

        public UpdateSupplierCommandHandler(
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<UpdateSupplierCommandHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改供应商命令
        /// </summary>
        /// <param name="request">修改供应商命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateSupplierCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始修改供应商，ID: {SupplierId}, 名称: {SupplierName}", 
                    request.Id, request.SupplierName);

                // 检查供应商是否存在
                var existingSupplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.Id == request.Id && !s.IsDeleted, cancellationToken);

                if (existingSupplier == null)
                {
                    _logger.LogWarning("供应商不存在或已被删除，ID: {SupplierId}", request.Id);
                    return ApiResult<bool>.Error("供应商不存在或已被删除");
                }

                // 验证供应商名称是否与其他供应商重复（排除当前供应商）
                var duplicateNameSupplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.SupplierName == request.SupplierName 
                                             && s.Id != request.Id 
                                             && !s.IsDeleted, cancellationToken);

                if (duplicateNameSupplier != null)
                {
                    _logger.LogWarning("供应商名称已存在，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, request.SupplierName);
                    return ApiResult<bool>.Error("供应商名称已存在，请使用其他名称");
                }

                // 更新供应商信息
                existingSupplier.SupplierName = request.SupplierName;
                existingSupplier.SupplierType = request.SupplierType;
                existingSupplier.ContactPhone = request.ContactPhone;
                existingSupplier.EntryUnit = request.EntryUnit;
                existingSupplier.UsageUnit = request.UsageUnit;
                existingSupplier.AffiliatedMarket = request.AffiliatedMarket;
                existingSupplier.ServicePersonnel = request.ServicePersonnel;
                existingSupplier.Status = request.Status;
                existingSupplier.ContactPersonName = request.ContactPersonName;
                existingSupplier.IdCard = request.IdCard;
                existingSupplier.UnifiedSocialCreditCode = request.UnifiedSocialCreditCode;
                existingSupplier.Industry = request.Industry;
                existingSupplier.MnemonicCode = request.MnemonicCode;
                existingSupplier.SupplierAttribute = request.SupplierAttribute;
                existingSupplier.Province = request.Province;
                existingSupplier.City = request.City;
                existingSupplier.District = request.District;
                existingSupplier.DetailedAddress = request.DetailedAddress;
                existingSupplier.Remarks = request.Remarks;
                existingSupplier.ModifiedBy = request.UpdatedBy?.ToString();
                existingSupplier.LastModifiedTime = DateTime.Now;
                existingSupplier.UpdatedTime = DateTime.Now;
                existingSupplier.UpdatedBy = request.UpdatedBy;

                // 执行更新操作
                var result = await _supplierRepository.UpdateAsync(existingSupplier);

                if (result > 0)
                {
                    _logger.LogInformation("成功修改供应商，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, request.SupplierName);
                    
                    return ApiResult<bool>.Success(true, "供应商修改成功");
                }
                else
                {
                    _logger.LogError("修改供应商失败，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, request.SupplierName);
                    
                    return ApiResult<bool>.Error("供应商修改失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改供应商时发生异常，ID: {SupplierId}, 名称: {SupplierName}", 
                    request.Id, request.SupplierName);
                
                return ApiResult<bool>.Error($"修改供应商时发生异常: {ex.Message}");
            }
        }
    }
} 